var express = require('express');
var router = express.Router();
var request = require('superagent');


var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://119.254.101.49');


client.on('connect', function () {
    console.log("is connect");
    client.subscribe('start');
    client.subscribe('stop');

    client.subscribe('query');
    client.subscribe('queryLoopStart');
    client.subscribe('queryLoopStop');
});

var interval;
var loopInterval;
client.on('message', function (topic, message) {
    if (topic == "start") {
        var time = Number(message);
        if (interval) {
            clearInterval(interval);
        }
        console.log("start-------");
        interval = setInterval(function () {
            client.publish('presence', 'Hello mqtt');
        }, time);

    } else if (topic == "stop") {
        console.log("stop-------" );
        if (interval) {
            clearInterval(interval);
        }

    } else if (topic == "query") {
        console.log("query");
        console.log("message="+message);
        var paramsArr = message.toString().split(",");

        console.log("http://172.17.0.4:9099/dataexpress/api/v1/messages?sTime="+paramsArr[0]+"&eTime="+paramsArr[1]+"&pageSize="+paramsArr[2]+"&currentPage="+paramsArr[3]);

        request
            .get("http://172.17.0.4:9099/dataexpress/api/v1/messages?sTime="+paramsArr[0]+"&eTime="+paramsArr[1]+"&pageSize="+paramsArr[2]+"&currentPage="+paramsArr[3])
            .end(function (err, sres) {
                console.log(sres.text);
            });



    } else if (topic == "queryLoopStart") {
        if (loopInterval) {
            clearInterval(loopInterval);
        }
        var time = Number(message);
        loopInterval = setInterval(function () {

            request
                .get("http://172.17.0.4:9099/dataexpress/api/v1/messages?pageSize=1000&currentPage=1")
                .end(function (err, sres) {
                    console.log("============");
                    console.log(sres.text);
                });
        }, time);


        console.log("queryLoop");
    }else if (topic == "queryLoopStop") {
        console.log("queryLoopStop-------" );
        if (loopInterval) {
            clearInterval(loopInterval);
        }
    }


});


/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});


module.exports = router;
